package com.scalar.chiptrack.operations.lotcorrection.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.dataentry.forms.AssemblyDataEntryForm;
import com.scalar.chiptrack.operations.dataentry.forms.InventoryDataEntryForm;
import com.scalar.chiptrack.operations.dataentry.forms.TestDataEntryForm;
import com.scalar.chiptrack.operations.lotcorrection.LotCorrection;
import com.scalar.chiptrack.operations.lotcorrection.dao.LotCorrectionDAO;
import com.scalar.chiptrack.operations.lotcorrection.forms.LotCorrectionForm;
import com.scalar.chiptrack.operations.process.Lot;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.FinishedGoods;
import com.scalar.chiptrack.operations.process.dao.LotDAO;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;

/**
 * Processes the requests from the lot correction screen
 *
 * Author  : rohan
 * Date    : Jul 27, 2004
 * Version : 1.0
 * Author  : ravikanth
 * Version : 1.1
 * Date    : Jan 19, 2004
 */
public class LotCorrectionAction extends ChipTrackAction
{
     private static final String ACTION_NAME = "/lotCorrection.do";

     public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws Exception
    {
        ActionForward actionForward = mapping.findForward(  "lotCorrection" );
        HttpSession session = request.getSession();

        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME );
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.LOT_CORRECTION, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

		HashMap     errors  = new HashMap();
		HashMap     info    = new HashMap();
        String      action  = request.getParameter ("action");
        LotCorrectionForm lotCorrectionForm = ( LotCorrectionForm )form;
        LotCorrection lotCorrection = lotCorrectionForm.getLotCorrection();
        request.setAttribute( "ListSize", "0" );

        /*
            Depending on the value of the action attribute request is processed

            Action Value       : Action Taken
            ------------		 ------------
            null               : Load the Types of Lot Correction
            lotCorrection	   : Load the list of processes
            loadProducts       : Loads the list of products in the selected process
            loadLocations      : Loads the list of location for the selected process and product
            loadLotStatus      : Loads the statuses of the lots matching the process, product and location
            loadLotNumbers     : Loads the lots matching the process, product, location and lot status
            loadLot            : Loads the details of the lot
            saveLot            : Saves the lot corrrection data in the database
        */
		if( action == null )
		{
			return mapping.findForward( "lotCorrectionType" );
		}
        else if( "lotCorrection".equalsIgnoreCase( action ) )
        {
            session.setAttribute( "processList",   getProcessList() );
            session.removeAttribute( "productList" );
            session.removeAttribute( "locationList" );
            session.removeAttribute( "lotNumberList" );
            lotCorrectionForm.setProcessType( "" );
            lotCorrectionForm.setProcessStepId( "" );
            lotCorrectionForm.setLocationId( "" );
            lotCorrectionForm.setLotId( "" );
            lotCorrection = new LotCorrection();
        }
        else if( "loadPSLineItems".equals( action ) )
        {
            try
            {
                String lotId = request.getParameter("lotId");
                request.setAttribute( "PackingSlipsMap", LotCorrectionDAO.loadPackingSlipsByLotId( null, lotId  ) );
            }
            catch( Exception e )
            {
                errors.put( "Error while retreiving the packing slip line items list", null );
            }
            return( mapping.findForward( "loadPSLineItems" ) );
        }
        else if( "revertLotLineItemQty".equals( action ) )
        {
            try
            {
                String[] csIds 	= request.getParameterValues ( "chkCsLineItemId" );
                if ( csIds != null && csIds.length > 0 )
                {
                    session.setAttribute( "selectedCSIds" , csIds);
                }
                else
                {
                    csIds = new String[] {};
                    session.setAttribute( "selectedCSIds" , csIds);
                }
            }
            catch( Exception e )
            {
                errors.put( "Error while retreiving the selected packing slip line items list", null );
            }
            request.setAttribute("CloseWindowAfterSave","true");
            return( mapping.findForward( "loadPSLineItems" ) );
        }
        else if( "loadProducts".equals( action ) )
        {
            try
            {
                session.setAttribute( "productList", getProductList( lotCorrectionForm.getProcessType() ) );
                session.removeAttribute( "locationList" );
                session.removeAttribute( "lotNumberList" );
                session.removeAttribute( "selectedCSIds" );
                if( "-1".equals( lotCorrectionForm.getProcessStepId() ) || "-2".equals( lotCorrectionForm.getProcessStepId() ) )
                {
                    errors.put( "Please Select Valid Product Name", null );
                }
                else
                {
                    lotCorrectionForm.setProcessStepId( "" );
                }
                lotCorrectionForm.setLocationId( "" );
                lotCorrectionForm.setLotId( "" );
                lotCorrection = new LotCorrection();
            }
            catch( Exception e )
            {
                errors.put( "Error while retreiving the product list", null );
            }
        }
        else if( "loadLocations".equals( action ) )
        {
            try
            {
                session.setAttribute( "locationList", getLocationList( lotCorrectionForm.getProcessStepId() ) );
                session.removeAttribute( "lotNumberList" );
                session.removeAttribute( "selectedCSIds" );
                lotCorrectionForm.setLocationId( "" );
                lotCorrectionForm.setLotId( "" );
                lotCorrection = new LotCorrection();
            }
            catch( Exception e )
            {
                errors.put( "Error while retreiving the location list", null );
            }
        }
        else if( "loadLotNumbers".equals( action ) )
        {
            try
            {
                session.removeAttribute( "selectedCSIds" );
                session.setAttribute( "lotNumberList", getLotList( lotCorrectionForm.getProcessType(), lotCorrectionForm.getProcessStepId(), lotCorrectionForm.getLocationId() ) );
                lotCorrectionForm.setLotId( "" );
                lotCorrection = new LotCorrection();
            }
            catch( Exception e )
            {
                errors.put( "Error while retreiving the lot numbers list", null );
            }
        }
        else if( "loadLot".equals( action ) )
        {
            try
            {
                lotCorrection = getLotCorrection( lotCorrectionForm.getProcessType(), lotCorrectionForm.getLotId(), lotCorrectionForm.getProcessStepId(), lotCorrectionForm.getLocationId() );

                if( lotCorrection.getNextStageLotList() != null )
                {
                    if( lotCorrection.getNextStageLotList().size() > 0 )
                    {
                        request.setAttribute( "ListSize", "1" );
                    }
                }
                session.removeAttribute( "selectedCSIds" );
            }
            catch( Exception e )
            {
                errors.put( "Error while retreiving the lot", null );
            }
        }
        else if( "allLotInfo".equals( action ) )
        {
            String lotprocessstepId = lotCorrectionForm.getProcessStepId();
            String lotlocationId = lotCorrectionForm.getLocationId();

            StringTokenizer st = new StringTokenizer ( lotprocessstepId, "$" );
            String pId = st.nextToken ();
            st.nextToken ();

            st = new StringTokenizer ( lotlocationId, "/" );
            String locId = st.nextToken ();
            st.nextToken ();

            ArrayList allLotsList = null;
            String lotNo = null;
            if ( lotCorrection.getLotNumber() != null )
            {
                lotNo = lotCorrection.getLotNumber().trim();
            }

            try
            {
                String lotId = LotDAO.getLotId( lotNo , locId, pId  );

                if ( lotId != null && lotId.length() > 0 )
                {
                    allLotsList = LotDAO.getAllLotDetails( lotId );
                }

                request.setAttribute("allLotsList", allLotsList );
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Error while retreiving the Lot history list", null );
            }
            return mapping.findForward( "alllotInfo" );
        }
        else if( "saveLot".equals( action ) )
        {
            try
            {
                if( LotCorrectionDAO.checkDuplicateLots( null, lotCorrection ) )
                {
                    if( lotCorrection.getNextStageLotList() != null )
                     {
                        if( lotCorrection.getNextStageLotList().size() > 0 )
                        {
                            request.setAttribute( "ListSize", "1" );
                        }
                    }
                    request.setAttribute( "ListSize", "2" );
                   errors.put( "Another lot is existing with this lot number", null );
                }
                else
                {
                    if( lotCorrection.isHold() )
                    {
						boolean isPackingSlipLineItemsExits =  false;

                        if( "Finished Goods".equals( lotCorrectionForm.getProcessType() ) )
                        {
							isPackingSlipLineItemsExits = LotCorrectionDAO.isLineItemsExitsByLotId( null, lotCorrection.getLotId() );
                        }

                        if( isPackingSlipLineItemsExits && session.getAttribute( "selectedCSIds" ) == null )
                        {
                            try
                            {
                                String[] csIds 	= request.getParameterValues ( "chkCsLineItemId" );
                                if ( csIds != null && csIds.length > 0 )
                                {
                                    session.setAttribute( "selectedCSIds" , csIds);
                                }
                                else
                                {
                                    csIds = new String[] {};
                                    session.setAttribute( "selectedCSIds" , csIds);
                                }
                            }
                            catch( Exception e )
                            {
                                errors.put( "Error while retreiving the selected packing slip line items list", null );
                            }
                            try
                            {
                                lotCorrection = getLotCorrection( lotCorrectionForm.getProcessType(), lotCorrectionForm.getLotId(), lotCorrectionForm.getProcessStepId(), lotCorrectionForm.getLocationId() );
                                if( lotCorrection.getNextStageLotList() != null )
                                {
                                    if( lotCorrection.getNextStageLotList().size() > 0 )
                                    {
                                        request.setAttribute( "ListSize", "1" );
                                    }
                                }
                                request.setAttribute( "DisplayPSLineItemsLink", isPackingSlipLineItemsExits + "");
                            }
                            catch( Exception e )
                            {
                                errors.put( "Error while retreiving the lot", null );
                            }
                            return actionForward;
                        }
                    }

                    //Added by KumaraSwamy on Nov18th, 2004.
                    String[] selectedCsIds = ( String[] ) session.getAttribute( "selectedCSIds" );
                    int selectedCsIdsLength = 0;
                    int  totCslntQtyShipped = 0;
                    int qtyPulled = 0;
                    int qtyIn = 0;

                    if( selectedCsIds != null )
                    {
                        selectedCsIdsLength = selectedCsIds.length;
                    }

                    for( int i = 0; i < selectedCsIdsLength; i++ )
                    {
                        int cslntQtyShipped = 0;
                        cslntQtyShipped 	= LotDAO.getCSLNTQuantityShiped( null, selectedCsIds[i] );
                        totCslntQtyShipped 	= totCslntQtyShipped + cslntQtyShipped;
                    }

                    qtyPulled = LotDAO.getCSLNTQuantityPulled ( null, lotCorrection.getLotId() );
                    qtyPulled = (qtyPulled - totCslntQtyShipped);

                    try
                    {
                        qtyIn = Integer.parseInt( lotCorrectionForm.getLotCorrection().getQuantityIn() );
                    }
                    catch(Exception e){}

                    if( qtyIn < qtyPulled )
                    {
                        errors.put ( "Quantity In should not be less than Packing Slip Issued quantity ( "+ qtyPulled+" )" , null);
                        if( !errors.isEmpty() )
                        {
                            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
                            boolean isPackingSlipLineItemsExits =  false;
                            isPackingSlipLineItemsExits = LotCorrectionDAO.isLineItemsExitsByLotId( null,  lotCorrection.getLotId() );
                            request.setAttribute( "DisplayPSLineItemsLink", isPackingSlipLineItemsExits + "");
                        }

                        return actionForward;
                    }

                    saveLot( lotCorrection );

                    //PACKINGSLIP CANCELLENTATION STARTS FROM HERE
                    selectedCsIds = ( String[] ) session.getAttribute( "selectedCSIds" );
                    //if( "Finished Goods".equals( lotCorrectionForm.getProcessType() ) && lotCorrection.isHold() && selectedCsIds != null && selectedCsIds.length > 0 )
                    if( "Finished Goods".equals( lotCorrectionForm.getProcessType() ) && selectedCsIds != null && selectedCsIds.length > 0 )  //Dodified by KumaraSwamy(11-17-04)
                    {
                        LotCorrectionDAO.cancelPackingSlips( null , selectedCsIds, lotCorrection.getLotId() );
                    }
                    //PACKINGSLIP CANCELLENTATION END FROM HERE
                    info.put( "Lot correction details updated successfully", null );
                    session.removeAttribute( "productList" );
                    session.removeAttribute( "locationList" );
                    session.removeAttribute( "lotNumberList" );
                    lotCorrectionForm.setProcessType( "" );
                    lotCorrectionForm.setProcessStepId( "" );
                    lotCorrectionForm.setLocationId( "" );
                    lotCorrectionForm.setLotId( "" );
                    lotCorrection = new LotCorrection();
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Error while saving the lot correction details", null );
            }
        }

        lotCorrectionForm.setLotCorrection( lotCorrection );
        if( !errors.isEmpty() )
        {
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
        }

        if( !info.isEmpty() )
        {
            request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        }
        return actionForward;
    }

    /**
     * Returns an arraylist of processes
     *
     * @return
     */
    public ArrayList getProcessList()
    {
        ArrayList processList = new ArrayList();
		processList.add( new org.apache.struts.util.LabelValueBean( "FAB", "FAB" ) );
        processList.add( new org.apache.struts.util.LabelValueBean( "WAFER STORE", "Wafer Store" ) );
		processList.add( new org.apache.struts.util.LabelValueBean( "SORT", "SORT" ) );
        processList.add( new org.apache.struts.util.LabelValueBean( "DIE BANK", "Die Bank" ) );
		processList.add( new org.apache.struts.util.LabelValueBean( "ASSEMBLY", "ASSEMBLY" ) );
		processList.add( new org.apache.struts.util.LabelValueBean( "TEST", "TEST" ) );
		processList.add( new org.apache.struts.util.LabelValueBean( "CLASS STORE", "Class Store" ) );
		processList.add( new org.apache.struts.util.LabelValueBean( "MARK&PACK", "Mark and Pack" ) );
		processList.add( new org.apache.struts.util.LabelValueBean( "FINISHED GOODS", "Finished Goods" ) );
        return processList;
    }


    /**
     * Returns the list of part number in the given process
     *
     * @param process
     * @return
     */
    public ArrayList getProductList( String process ) throws ScalarException
    {
        ArrayList partNumberSelectList = new ArrayList ();
        ArrayList partNumberList       = null;
        PartNumber partNumber = null;

        if( ( "FAB".equals( process ) ) ||
            ( "SORT".equals( process ) ) ||
            ( "ASSEMBLY".equals( process ) ) ||
            ( "TEST".equals( process ) ) )
        {
            partNumberList = ProductDao.getPartNumber ( process );
            for ( int i = 0; i < partNumberList.size (); i++ )
            {
                partNumber = ( PartNumber ) partNumberList.get ( i );
                partNumberSelectList.add ( new org.apache.struts.util.LabelValueBean ( partNumber.getPartNumber (), partNumber.getProcessStepId () + "$" + partNumber.getPartNumber () ) );
            }
        }
        else if ( ( "Wafer Store".equals( process ) ) ||
                  ( "Die Bank".equals( process ) ) ||
                  ( "Class Store".equals( process ) ) ||
                  ( "Mark and Pack".equals( process ) ) /*||
                  ( "Finished Goods".equals( process ) )*/ )
        {
            String processSearchString = "";
            if( ( "Wafer Store".equals( process ) ) )
            {
                processSearchString = "wafer%";
            }
            if( ( "Die Bank".equals( process ) ) )
            {
                processSearchString = "die%";
            }
            if( ( "Class Store".equals( process ) ) )
            {
                processSearchString = "class%";
            }
            if( ( "Mark and Pack".equals( process ) ) )
            {
                processSearchString = "mark%";
            }
            /*if( ( "Finished Goods".equals( process ) ) )
            {
                processSearchString = "finished%";
            }*/
            partNumberList = ProductDao.getInventoryPartNumber( processSearchString );
            for( int i=0; i<partNumberList.size(); i++ )
            {
	            partNumber = (PartNumber)partNumberList.get(i);
	            String partNo = partNumber.getPartNumber();
	            StringTokenizer someValue = new StringTokenizer(partNo,"/");
	            String finalPartNo =  someValue.nextToken();
	            partNumberSelectList.add(new LabelValueBean(finalPartNo, partNumber.getProcessStepId()+"$"+finalPartNo));
            }
        }
        else if ( ( "Finished Goods".equals( process ) ) )
        {
            try{
                partNumberSelectList = loadManufacturingProducts();
            }
            catch( Exception e)
            {
                e.printStackTrace();
            }
        }

        return partNumberSelectList;
    }

    /**
     * Returns the list of locations of this process step
     *
     * @param processStepId
     * @return
     */
    public ArrayList getLocationList( String processStepId ) throws ScalarException
    {
        StringTokenizer st1 = new StringTokenizer ( processStepId, "$" );
        String pId = st1.nextToken ();
        st1.nextToken ();

        ArrayList locationList = VendorDAO.getSelectedLocations ( Integer.parseInt ( pId ) );
        ArrayList locationSelectList = new ArrayList();
        VendorLocation vendorLocation = null;

        for ( int i = 0; i < locationList.size (); i++ )
        {
            vendorLocation = ( VendorLocation ) locationList.get ( i );
            locationSelectList.add ( new org.apache.struts.util.LabelValueBean ( vendorLocation.getLocationName(), vendorLocation.getLocationID() + "/" + vendorLocation.getLocationName() ) );
        }

        return locationSelectList;
    }

    /**
     * Returns the list of lots matching the given processStepId and locationId
     *
     * @param processStepId
     * @param locationId
     * @return
     */
    private ArrayList getLotList( String processStep, String processStepId, String locationId) throws ScalarException
    {
        ArrayList lotList = new ArrayList();
        Lot lot = null;
        StringTokenizer st = new StringTokenizer ( processStepId, "$" );
        String pId = st.nextToken ();
        st.nextToken ();

        st = new StringTokenizer ( locationId, "/" );
        String locId = st.nextToken ();
        st.nextToken ();

        ArrayList lotNumberList = LotDAO.getAllLots ( pId, locId );
        lotList = new ArrayList ();

        for ( int i = 0; i < lotNumberList.size (); i++ )
        {
            lot = ( Lot ) lotNumberList.get ( i );

            //Modified by KumaraSwamy on August 12th 2004
            if( ( "Finished Goods".equalsIgnoreCase( processStep ) )&&( "Close".equalsIgnoreCase( lot.getStatus () ) ) )
            {
                // It is for not adding the Finished goods Closed lots to lotList
            }
            else
            {
                lotList.add ( new org.apache.struts.util.LabelValueBean ( lot.getLotNumber (), lot.getLotId () + "$" + lot.getLotNumber () + "$" + lot.getStatus () ) );
            }
        }
        return lotList;
    }

    /**
     * Returns the lot pertaining to the given lot ID
     *
     * @param processType
     * @param lotId
     * @return
     * @throws ScalarException
     */
    private LotCorrection getLotCorrection( String processType, String lotId, String processStepId, String locationId ) throws ScalarException
    {
        LotCorrection lotCorrection = null;
        StringTokenizer st = new StringTokenizer ( lotId, "$" );
        String strLotId = st.nextToken ();
        if( st.hasMoreTokens() )
        {
            st.nextToken ();
        }
        if( st.hasMoreTokens() )
        {
            st.nextToken ();
        }

        st = new StringTokenizer ( processStepId, "$" );
        String strPId     = st.nextToken ();
        if( st.hasMoreTokens() )
        {
            st.nextToken ();
        }

        st = new StringTokenizer ( locationId, "/" );
        String locId = st.nextToken ();
        if( st.hasMoreTokens() )
        {
            st.nextToken ();
        }

        lotCorrection = LotDAO.fetchLotInformation( strLotId );

        /*if( "FAB".equals( processType ) )
        {
            lotCorrection = getLotCorrectionFromLot( LotDAO.getFabLotData( strLotId ), processType );
        }
        else if( "SORT".equals( processType ) )
        {
            lotCorrection = getLotCorrectionFromLot( LotDAO.getSortLotData( strLotId ), processType );
        }
        else if( "ASSEMBLY".equals( processType ) )
        {
            lotCorrection = getLotCorrectionFromAssemblyDataEntryForm( LotDAO.getAssemblyLotData( strLotId ) );
        }
        else if( "TEST".equals( processType ) )
        {
            lotCorrection = getLotCorrectionFromTestDataEntryForm( LotDAO.getTestLotData( strLotId ) );
        }
        else if ( ( "Wafer Store".equals( processType ) ) ||
                  ( "Die Bank".equals( processType ) ) ||
                  ( "Class Store".equals( processType ) ) ||
                  ( "Mark and Pack".equals( processType ) ) ||
                  ( "Finished Goods".equals( processType ) ) )
        {
            lotCorrection = getLotCorrectionFromInventoryDataEntryForm( LotDAO.getInventoryLotData( strLotId ) );
        }*/

        if( lotCorrection == null )
        {
            lotCorrection = new LotCorrection();
        }
        else
        {
            lotCorrection.setLotId( strLotId );
            lotCorrection.setLocationId( locId );
            lotCorrection.setProcessStepId( strPId );
            lotCorrection.setProcessType( processType );

            //lot status is displayed as Wip when it is in running state
            if( Constants.LOT_STATUS_RUNNING.equals( lotCorrection.getLotStatus() ) )
            {
                lotCorrection.setLotStatus( LotCorrection.LOT_STATUS_WIP );
            }

            if( ( "Close".equals( lotCorrection.getLotStatus() ) ) )
            {
                //setting the lot details in the next stage
                lotCorrection.setNextStageLotList( LotCorrectionDAO.getLotsInNextImmediateStage( null, lotCorrection.getLotId() ) );
            }

            //if no lots are retreived then setting the list as null
            if( lotCorrection.getNextStageLotList().size() == 0 )
            {
                lotCorrection.setNextStageLotList( null );
            }

        }
        return lotCorrection;
    }

    /**
     * Constructs the lot correction object from the lot object
     *
     * @param lot
     * @return
     */
    public LotCorrection getLotCorrectionFromLot( Lot lot, String psType )
    {
        LotCorrection lotCorrection = new LotCorrection();

        lotCorrection.setLotId           ( lot.getLotId() );
        lotCorrection.setLotNumber       ( lot.getLotNumber() );
        lotCorrection.setLotStatus       ( lot.getStatus() );
        lotCorrection.setDateIn          ( lot.getDateIn() );
        lotCorrection.setDateOut         ( lot.getDateOut() );
        lotCorrection.setDateCode        ( lot.getDateCode() );
        lotCorrection.setQuantityIn      ( lot.getQuantityIn() );
        lotCorrection.setQuantityOut     ( lot.getQuantityOut() );
        lotCorrection.setDieSize         ( lot.getDieSize() );
        lotCorrection.setVendorLotNumber ( lot.getVendorLot() );
        lotCorrection.setLotComments     ( lot.getComments() );
        if( "FAB".equals( psType ) )
        {
            lotCorrection.setGrossDie   ( lot.getGrossDie() );
        }
        else
        lotCorrection.setGrossDie   ( lot.getDieWafer() );
        lotCorrection.setHold       ( lot.isHold() );

        return lotCorrection;
    }

    /**
     * Constructs the lot correction object from the test data entry form object
     *
     * @param testDataEntryForm
     * @return
     */
    public LotCorrection getLotCorrectionFromTestDataEntryForm( TestDataEntryForm testDataEntryForm )
    {
        LotCorrection lotCorrection = new LotCorrection();

        lotCorrection.setLotId           ( testDataEntryForm.getLotId() );
        lotCorrection.setLotNumber       ( testDataEntryForm.getLotNo() );
        lotCorrection.setLotStatus       ( testDataEntryForm.getStatus() );
        lotCorrection.setDateIn          ( testDataEntryForm.getDateIn() );
        lotCorrection.setDateOut         ( testDataEntryForm.getDateOut() );
        lotCorrection.setDateCode        ( testDataEntryForm.getDateCode() );
        lotCorrection.setQuantityIn      ( testDataEntryForm.getQuantityIn() );
        lotCorrection.setQuantityOut     ( testDataEntryForm.getQuantityOut() );
        lotCorrection.setVendorLotNumber ( testDataEntryForm.getVendorLot() );
        lotCorrection.setLotComments     ( testDataEntryForm.getComments() );
        lotCorrection.setHold            ( testDataEntryForm.isHold());

        return lotCorrection;
    }

    /**
     * Constructs the lot correction object from the assembly data entry form object
     *
     * @param assemblyDataEntryForm
     * @return
     */
    public LotCorrection getLotCorrectionFromAssemblyDataEntryForm( AssemblyDataEntryForm assemblyDataEntryForm )
    {
        LotCorrection lotCorrection = new LotCorrection();

        lotCorrection.setLotId           ( assemblyDataEntryForm.getLotId() );
        lotCorrection.setLotNumber       ( assemblyDataEntryForm.getLotNo() );
        lotCorrection.setLotStatus       ( assemblyDataEntryForm.getLotStatus() );
        lotCorrection.setDateIn          ( assemblyDataEntryForm.getDateIn() );
        lotCorrection.setDateOut         ( assemblyDataEntryForm.getDateOut() );
        lotCorrection.setDateCode        ( assemblyDataEntryForm.getDateCode() );
        lotCorrection.setQuantityIn      ( assemblyDataEntryForm.getQuantityIn() );
        lotCorrection.setQuantityOut     ( assemblyDataEntryForm.getQuantityOut() );
        lotCorrection.setVendorLotNumber ( assemblyDataEntryForm.getVendorLotNo() );
        lotCorrection.setLotComments     ( assemblyDataEntryForm.getComments() );
        lotCorrection.setHold            ( assemblyDataEntryForm.isHold() );

        return lotCorrection;
    }

    /**
     * Constructs the lot correction object from the inventory data entry form object
     *
     * @param inventoryDataEntryForm
     * @return
     */
    public LotCorrection getLotCorrectionFromInventoryDataEntryForm( InventoryDataEntryForm inventoryDataEntryForm )
    {
        LotCorrection lotCorrection = new LotCorrection();

        lotCorrection.setLotId           ( inventoryDataEntryForm.getLotId() );
        lotCorrection.setLotNumber       ( inventoryDataEntryForm.getLotNo() );
        lotCorrection.setLotStatus       ( inventoryDataEntryForm.getLotStatus() );
        lotCorrection.setDateIn          ( inventoryDataEntryForm.getDateIn() );
        lotCorrection.setDateOut         ( inventoryDataEntryForm.getDateOut() );
        lotCorrection.setDateCode        ( inventoryDataEntryForm.getDateCode() );
        lotCorrection.setQuantityIn      ( inventoryDataEntryForm.getQuantityIn() );
        lotCorrection.setQuantityOut     ( inventoryDataEntryForm.getQuantityOut() );
        lotCorrection.setVendorLotNumber ( inventoryDataEntryForm.getVendorLot() );
        lotCorrection.setLotComments     ( inventoryDataEntryForm.getComments() );
        lotCorrection.setHold            ( inventoryDataEntryForm.isHold() );

        return lotCorrection;
    }

    /**
     * saves the lot correction data and the data pertaining to the next stages if existing
     *
     * @param lotCorrection
     * @return
     * @throws ScalarException
     */
    public boolean saveLot( LotCorrection lotCorrection ) throws ScalarException
    {
        boolean success = true;
        LotCorrectionDAO.saveLotCorrection( null, lotCorrection, false );
        LotCorrection nextLotCorrection = null;

        //saving the modification to the lots in the next stage
        if( lotCorrection.getNextStageLotList() != null )
        {
            for( int i = 0; i < lotCorrection.getNextStageLotList().size(); i++ )
            {
                nextLotCorrection = ( LotCorrection )lotCorrection.getNextStageLotList().get( i );
                if( nextLotCorrection.isModify() )
                {
                    LotCorrectionDAO.saveLotCorrection( null, nextLotCorrection, true );
                }
            }
        }
        return  success;
    }

    public static ArrayList loadManufacturingProducts () throws Exception
    {
        ArrayList parts = new ArrayList ();

        Iterator list = FinishedGoodsDAO.loadAllParentPartNumbersByType().iterator ();

        //parts.add ( new org.apache.struts.util.LabelValueBean ( "All Products", "0" ) );

        while ( list.hasNext () )
        {
            FinishedGoods product = ( FinishedGoods ) list.next ();

            if( "---- BOARD -----".equalsIgnoreCase( product.getManufacturingPartNo() ) )
            {
                parts.add ( new org.apache.struts.util.LabelValueBean ( product.getManufacturingPartNo (), "-1" ) );
            }
            else if( "---- KIT -----".equalsIgnoreCase( product.getManufacturingPartNo() ) )
            {
                parts.add ( new org.apache.struts.util.LabelValueBean ( product.getManufacturingPartNo (), "-2" ) );
            }
            else
            {
                parts.add ( new org.apache.struts.util.LabelValueBean ( product.getManufacturingPartNo (), product.getProcessStepId()+"$"+product.getManufacturingPartNo () ) );
            }
        }

        return parts;
    }
}
